<!--
 * @Author: 半生瓜 1515706227@qq.com
 * @Date: 2024-05-06 19:31:40
 * @LastEditors: 半生瓜 1515706227@qq.com
 * @LastEditTime: 2024-05-22 14:51:25
 * @FilePath: \vue-element-plus-admin-mini\src\views\zy\Menu12.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="tsx">
import {
  ElInput,
  ElButton,
  ElRadio,
  ElRadioButton,
  ElTree,
  ElMessageBox,
  ElMessage,
  FormItemRule
} from 'element-plus'
import { onBeforeRouteUpdate, useRoute } from 'vue-router'
import { ref, watch } from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn, TableSlotDefault } from '@/components/Table'
import { getRoleAll, getRole, getAuthTree, saveRole, deleteRole, getRoleDetail } from '@/api/role'
import { reactive, unref, onMounted } from 'vue'
import { useTable } from '@/hooks/web/useTable'
import { Dialog } from '@/components/Dialog'
import { Form, FormSchema, RadioOption } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'
import { BaseButton } from '@/components/Button'
import { Search, Edit, Delete } from '@element-plus/icons-vue'
import { any } from 'vue-types'
import router from '@/router'
const { required, onlyEnglish } = useValidator()

const route = useRoute()

watch(route, (newValue, oldValue) => {
  console.log(`Message changed from "${oldValue}" to "${newValue}"`)
})

defineOptions({
  name: 'TemplateManage'
})

//提交角色参数
let query = {
  roleName: '',
  enName: '',
  authorityList: [] as any
}
//编辑角色参数
let query2 = {
  roleName: '',
  enName: '',
  roleId: '',
  authorityList: [] as any
}

let morenxz = reactive([] as any)

//角色列表
const rolelists = reactive([] as { label: any; value: any }[])
onMounted(async () => {
  const res = await getRoleAll()
  res.data.map((item) => {
    let a1 = {
      label: item.roleName,
      value: String(item.roleId)
    }
    rolelists.push(a1)
  })
  console.log('okokokokoko', rolelists)
})

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getRole({
      page: unref(currentPage),
      pageSize: unref(pageSize),
      roleName: unref(roleName)
    })
    return {
      list: res.data.content,
      total: res.data.totalElements
    }
  }
})
let isedit = ref('编辑')
const { loading, dataList, total, currentPage, pageSize } = tableState
const { refresh, getElTableExpose } = tableMethods
const { t } = useI18n()
const { formRegister, formMethods } = useForm()
const { getElFormExpose, getFormData } = formMethods
const columns = reactive<TableColumn[]>([
  {
    field: 'selection',
    type: 'selection'
  },
  {
    field: 'roleName',
    label: '角色名称'
  },
  {
    field: 'auths',
    label: '功能权限'
  },
  {
    field: 'updateTime',
    label: '更新时间'
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    slots: {
      default: (data) => {
        return (
          <>
            <ElButton type="primary" onClick={() => editRole(data)}>
              {t('tableDemo.edit')}
            </ElButton>
            <ElButton type="danger" onClick={() => handerdeleteRole(data)}>
              {t('tableDemo.delete')}
            </ElButton>
          </>
        )
      }
    }
  }
])

let newroleId = ref('')

//编辑
const editRole = async (data) => {
  isedit.value = '编辑'
  morenxz = []
  console.log('sadasd11', isedit)

  newroleId.value = data.row.roleId
  const res = await getRoleDetail({ roleId: data.row.roleId })
  console.log('kankna===', res)
  query2.authorityList = res.data.authorityList
  res.data.authorityList.map((item) => {
    if (item == 1) {
      morenxz.push(1)
    }
    if (item == 3) {
      morenxz.push(2)
    }
    if (item == 5) {
      morenxz.push(3)
    }
    if (item == 10) {
      morenxz.push(7)
    }
    if (item == 10) {
      morenxz.push(7)
    }
    if (item == 8) {
      morenxz.push(5)
    }
    if (item == 9) {
      morenxz.push(6)
    }
  })

  tianjia().then(async () => {
    const formData = await getFormData()
    formData.roleName = res.data.roleName
    formData.enName = res.data.enName
    console.log('sssssa131', 22)
  })
}
//删除
const handerdeleteRole = async (data) => {
  ElMessageBox.confirm('确定删除该数据?')
    .then(async () => {
      let arr = {
        roleIds: [data.row.roleId]
      }
      const res = await deleteRole(arr)

      if (res.code == 200) {
        ElMessage.success('删除成功')
      }
      refresh()
    })
    .catch(() => {
      // catch error
    })
}
const roleName = ref('')
const isshow = ref(true)

interface Tree {
  label: string
  children?: Tree[]
}

let data: Tree[] = []

//搜索
const handersearch = function () {
  tableState.currentPage.value = 1
  refresh()
}

const tianjiabox = () => {
  isedit.value = '添加'
  query.authorityList = []
  query2.authorityList = []
  morenxz = []
  tianjia()
}
const tianjia = async () => {
  let res = await getAuthTree()
  console.log('kanjiiiiiiii', res)
  //处理树状结构
  const transformedData = [
    {
      label: '模板管理',
      id: 1,
      value: [2, 1]
    },
    {
      label: '资源管理',
      id: 2,
      value: [4, 3]
    },
    {
      label: '审核管理',
      id: 3,
      value: [6, 5]
    },
    {
      label: '权限管理',
      id: 4,
      value: [7],
      children: [
        {
          label: '用户管理',
          id: 5,
          value: 8
        },
        {
          label: '角色管理',
          id: 6,
          value: 9
        }
      ]
    },
    {
      label: '系统设置',
      id: 7,
      value: [11, 10]
    }
  ]

  data = transformedData
  isshow.value = false
}

const handleNodeClick = (data: Tree) => {
  console.log(data)
}

const defaultProps = {
  children: 'children',
  label: 'label'
}

const tijiao = async () => {
  const formRef = await getElFormExpose()

  if ([...new Set(query2.authorityList.flat(Infinity))].length !== 0) {
    await formRef?.validate(async (isValid) => {
      if (isValid) {
        const formData = await getFormData()
        console.log('sdaasdasdas', isedit)
        if (isedit.value == '编辑') {
          console.log('sadasd1111', newroleId.value)

          query2.roleId = newroleId.value
          console.log('asdasdiddiididid', query2.roleId)
          query2.roleName = formData.roleName
          query2.enName = formData.enName
          query2.authorityList = [...new Set(query2.authorityList.flat(Infinity))]
          let res1 = await saveRole(query2)
          console.log('kankanwwwww222', res1)
          if (res1.code == 200) {
            isshow.value = true
            ElMessage.success('编辑成功')
            refresh()
          }
        } else {
          query.roleName = formData.roleName
          query.enName = formData.enName
          query.authorityList = [...new Set(query.authorityList.flat(Infinity))]
          let res1 = await saveRole(query)
          console.log('kankanwwwww', res1)
          if (res1.code == 200) {
            isshow.value = true
            ElMessage.success('添加成功')
            refresh()
          }
        }
      }
    })
  } else {
    ElMessage.warning('请选择功能权限')
  }
}

const rules = reactive<{
  [key: string]: FormItemRule[]
}>({
  enName: [
    required(),
    { validator: (rule, value, callback) => onlyEnglish(value, callback, '请输入英文') }
  ]
})

const schema = reactive<FormSchema[]>([
  {
    field: 'roleName',
    label: '角色名称',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      placeholder: '请输入角色名称'
    },
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'enName',
    label: '英文名称',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      placeholder: '请输入英文名称'
    }
  }
])

const send = (a, b) => {
  //每次点击节点树会触发的事件，默认有两个参数
  console.log('a,b', a, b)
  query2.authorityList = []
  query.authorityList = []
  b.checkedNodes.map((item) => {
    query.authorityList.push(item.value)
    query2.authorityList.push(item.value)
  })
}

//多选删除
const getSelections = async () => {
  const elTableRef = await getElTableExpose()
  const selections = elTableRef?.getSelectionRows()

  let arr = {
    roleIds: []
  }
  if (selections) {
    arr.roleIds = selections.map((item) => {
      return item.roleId
    })
  }
  if (arr.roleIds.length !== 0) {
    ElMessageBox.confirm('确定删除所选数据?')
      .then(async () => {
        const res = await deleteRole(arr)
        if (res.code == 200) {
          ElMessage.success('删除成功')
        }
        refresh()
      })
      .catch(() => {
        // catch error
      })
  } else {
    ElMessage.warning('请选择数据')
  }
}
</script>

<template>
  <ContentWrap v-if="isshow">
    <div style="margin-bottom: 10px">
      <span style="color: #606266"> 角色名称：</span>
      <el-input
        v-model="roleName"
        style="width: 200px; height: 43px; margin: 7px"
        placeholder="请输入角色名称"
      />
      <ElButton type="primary" size="large" @click="handersearch" :icon="Search">搜索</ElButton>
      <ElButton type="success" size="large" @click="tianjiabox" :icon="Edit">添加</ElButton>
      <ElButton type="danger" size="large" @click="getSelections" :icon="Delete">删除</ElButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="columns"
      :data="dataList"
      row-key="id"
      headerAlign="center"
      align="center"
      :loading="loading"
      sortable
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>
  <ContentWrap
    v-if="!isshow"
    style="display: flex; position: relative; justify-content: space-between"
  >
    <Form :schema="schema" :rules="rules" @register="formRegister" />
  </ContentWrap>
  <br />
  <ContentWrap
    v-if="!isshow"
    style="display: flex; position: relative; justify-content: space-between"
  >
    <div style="padding-bottom: 10px">
      <img style="margin-top: -20px" src="../../assets/imgs/diandian.png" alt="" srcset="" />
      选择功能权限：</div
    >
    <el-tree
      style="max-width: 600px"
      show-checkbox
      :data="data"
      node-key="id"
      :default-checked-keys="morenxz"
      :props="defaultProps"
      @check="send"
    />
    <BaseButton
      @click="tijiao"
      style="font-size: 1rem; height: 2rem; position: absolute; top: 20px; right: 10px"
      type="primary"
      class="w-[75px]"
    >
      提交
    </BaseButton>
  </ContentWrap>
</template>
